package com.example.qt.ptplatform.service.impl;

import com.example.qt.ptplatform.entity.LoginLog;
import com.example.qt.ptplatform.mapper.LoginLogMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Service
public class LoginLogServiceImpl {
    @Autowired
    private LoginLogMapper loginLogMapper;

    // 记录登录日志
    public void recordLoginLog(Integer userId, HttpServletRequest request) {
        // 获取用户 IP 地址
        String ipAddress = getClientIp(request);

        // 获取用户地理位置
        String location = getGeolocation(ipAddress);

        // 创建并保存登录记录
        LoginLog loginLog = new LoginLog();
        loginLog.setUserId(userId);
        loginLog.setIpAddress(ipAddress);
        loginLog.setLoginTime(LocalDateTime.now());
        loginLog.setLocation(location);

        // 插入登录记录
        loginLogMapper.insertLoginLog(loginLog);
    }

    // 获取客户端 IP 地址
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    // 获取 IP 地址的地理位置
    private String getGeolocation(String ip) {
        String url = "https://ipwho.is/" + ip + "?fields=country,region,city";
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        // 解析 JSON 响应
        try {
            // 使用 Jackson ObjectMapper 解析 JSON 响应
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(response);

            // 获取需要的地理位置信息
            String country = jsonNode.path("country").asText();
            String region = jsonNode.path("region").asText();
            String city = jsonNode.path("city").asText();

            // 返回格式化后的地理位置字符串
            return country + ", " + region + ", " + city;
        } catch (Exception e) {
            // 如果出现异常，打印错误并返回一个默认值
            e.printStackTrace();
            return "Unknown Location";
        }
    }
}
